<template>
  <a-modal
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :title="title"
    :visible="visible"
    :width="1200"
    switchFullscreen
    okText="提交"
    @cancel="handleCancel"
    @ok="handleOk(type)"
  >
    <template slot="footer">
      <div>
        <a-button v-if="type == 1" type="primary" @click="handleOk">修改</a-button>
        <a-button  @click="close">关闭</a-button>
      </div>
    </template>
    <a-card :bordered="false" v-if="type == 1">
      <a-form :form="form">
        <a-row>
          <a-col :sm="12" :xs="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="知识库类型">
              <a-select
                v-decorator="['type', { rules: [{ required: false, message: '请选择咨询类型' }] }]"
                placeholder="请选择咨询类型"
              >
                <a-select-option
                  v-for="item in baseType"
                  :key="item.key"
                  :value="item.key"
                >{{ item.value }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :sm="12" :xs="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="标题">
              <a-input
                v-decorator="['tittle', { rules: [{ required: true, message: '请输入标题', trigger: 'blur' }]
                }]"
                placeholder="请输入标题"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :sm="12" :xs="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="关键字类型">
              <a-select mode="tags" placeholder="请输入关键字类型" v-decorator="['keywords', { rules: [{ required: false, message: '请选择关键词' }] }]">
                <a-select-option
                  v-for="item in  keyWordsList"
                  :key="item"
                  :value="item"
                >{{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :sm="12" :xs="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="原文链接">
              <a-input
                v-decorator="['url', { rules: [{ required: false, message: '请输入原文链接', trigger: 'blur' }]
                }]"
                placeholder="请输入原文链接"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :sm="12" :xs="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="文件上传">
              <a-upload-dragger
                :file-list="fileList"
                name="file"
                :multiple="false"
                :remove="handleRemove"
                :before-upload="beforeUpload"
              >
                <p class="ant-upload-drag-icon">
                  <a-icon type="inbox"/>
                </p>
                <p class="ant-upload-text">
                  请轻击此处选择文件或将文件直接拖拽进框内
                </p>
                <p class="ant-upload-hint">
                  支持单文件上传
                </p>
              </a-upload-dragger>
              <a-button style="margin-left: 68%" type="primary" @click="downloadFile"
                        v-show="this.model.fileId !== '' || this.model.fileId !== null ">点击下载文件
              </a-button>
            </a-form-item>
          </a-col>
          <a-col :sm="12" :xs="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="文件描述">
              <!--              <a-textarea v-decorator="['content', { rules: [{ required: false, message: '请输入文件描述', trigger: 'blur' }]-->
              <!--                }]" :value="value" placeholder="请输入文件描述" :rows="6" style="margin-top: 5px;"/>-->
              <a-textarea v-decorator="['content', { rules: [{ required: false, message: '请输入文件描述', trigger: 'blur' }]
                }]" placeholder="请输入文件描述" :rows="6" style="margin-top: 5px;"/>
            </a-form-item>
          </a-col>

        </a-row>

      </a-form>

      <a-modal v-model="modalShow" :title="modalTitle" ok-text="确认" cancel-text="取消" @ok="hideModal">
        <div style='display: flex;justify-content: center;align-items: center'>
          <p style='word-break: keep-all;margin: 0 30px 0'>模板名称</p>
          <a-input style='width: 300px'/>
        </div>
      </a-modal>
    </a-card>

    <!--    查看type=2，只读-->
    <a-card :bordered="false" v-if="type == 2">
      <a-form :form="form">
        <a-row>
          <a-col :sm="12" :xs="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="知识库类型">
              <!--              <a-select-->
              <!--                v-decorator="['type', { rules: [{ required: false, message: '请选择咨询类型' }] }]"-->
              <!--                placeholder="请选择咨询类型"-->
              <!--              >-->
              <!--                <a-select-option-->
              <!--                  v-for="item in baseType"-->
              <!--                  :key="item.key"-->
              <!--                  :value="item.key"-->
              <!--                >{{ item.value }}-->
              <!--                </a-select-option>-->
              <!--              </a-select>-->
              <a-input

                v-model="model.type"

                placeholder="暂无咨询类型"
                read-only
              />

            </a-form-item>
          </a-col>
          <a-col :sm="12" :xs="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="标题">
              <a-input
                v-decorator="['tittle', { rules: [{ required: true, message: '请输入标题', trigger: 'blur' }]
                }]"
                placeholder="请输入标题"
                read-only
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :sm="12" :xs="24">
<!--            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="关键字类型">-->
<!--              &lt;!&ndash;              <a-select mode="tags" style="width: 100%" placeholder="请输入关键字类型" v-decorator="['keywords', {}]">&ndash;&gt;-->
<!--              &lt;!&ndash;                <a-select-option v-for="i in 25" :key="(i + 9).toString(36) + i">&ndash;&gt;-->
<!--              &lt;!&ndash;                  {{ (i + 9).toString(36) + i }}&ndash;&gt;-->
<!--              &lt;!&ndash;                </a-select-option>&ndash;&gt;-->
<!--              &lt;!&ndash;              </a-select>&ndash;&gt;-->
<!--              <a-input-->

<!--                v-model="model.keywords"-->

<!--                placeholder="暂无咨询类型"-->
<!--                read-only-->
<!--              />-->
<!--            </a-form-item>-->
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="关键字类型">
              <a-select mode="tags" placeholder="请输入关键字类型" v-decorator="['keywords', { rules: [{ required: false, message: '请选择关键词' }] }]" :disabled="true">
                <a-select-option
                  v-for="item in  keyWordsList"
                  :key="item"
                  :value="item"
                >{{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :sm="12" :xs="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="原文链接">
              <a-input
                v-decorator="['url', { rules: [{ required: false, message: '请输入原文链接', trigger: 'blur' }]
                }]"
                placeholder="请输入原文链接"
                read-only
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :sm="12" :xs="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="文件下载">
              <!--              <a-upload-dragger-->
              <!--                name="file"-->
              <!--                :multiple="true"-->
              <!--              >-->
              <!--                <p class="ant-upload-drag-icon">-->
              <!--                  <a-icon type="inbox"/>-->
              <!--                </p>-->
              <!--                <p class="ant-upload-text">-->
              <!--                  请轻击此处选择文件或将文件直接拖拽进框内-->
              <!--                </p>-->
              <!--                <p class="ant-upload-hint">-->
              <!--                  支持单文件或多文件上传-->
              <!--                </p>-->
              <!--              </a-upload-dragger>-->
              <a-button type="primary" @click="downloadFile">点击下载</a-button>
            </a-form-item>
          </a-col>
          <a-col :sm="12" :xs="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="文件描述">
              <!--              <a-textarea v-decorator="['content', { rules: [{ required: false, message: '请输入文件描述', trigger: 'blur' }]-->
              <!--                }]" :value="value" placeholder="请输入文件描述" :rows="6" style="margin-top: 5px;" read-only/>-->
              <a-textarea v-decorator="['content', { rules: [{ required: false, message: '请输入文件描述', trigger: 'blur' }]
                }]" placeholder="请输入文件描述" :rows="6" style="margin-top: 5px;" read-only/>
            </a-form-item>
          </a-col>

        </a-row>

      </a-form>

      <a-modal v-model="modalShow" :title="modalTitle" ok-text="确认" cancel-text="取消" @ok="hideModal">
        <div style='display: flex;justify-content: center;align-items: center'>
          <p style='word-break: keep-all;margin: 0 30px 0'>模板名称</p>
          <a-input style='width: 300px'/>
        </div>
      </a-modal>
    </a-card>

  </a-modal>
  <!--  </a-spin>-->
  <!--  </j-modal>-->
</template>

<script>
import { getAction, httpAction, putAction, postAction } from '@/api/manage'
import axios from 'axios'
import qs from 'qs'
import Vue from 'vue'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import { mapGetters } from 'vuex'
import store from '@comp/tools/DepartSelect'

export default {
  name: 'newKnowledge',
  data() {
    return {
      modalShow: false,
      modalTitle: '另存为模板',
      type: '',
      value: '',
      fileList: [],
      baseType: [
        {
          key: 1,
          value: '政策文件类'
        }, {
          key: 2,
          value: '申请流程类'
        }, {
          key: 3,
          value: '需求咨询类'
        }, {
          key: 4,
          value: '建议意见类'
        }, {
          key: 5,
          value: '投诉举报类'
        }
      ],
      selectList: [
        {
          id: 1,
          option: '2021款汉DMI'
        },
        {
          id: 2,
          option: '选项1'
        },
        {
          id: 3,
          option: '选项2'
        },
        {
          id: 4,
          option: '选项3'
        }
      ],
      record: '',
      title: '交易信息',
      visible: false,
      model: {},
      noChooseBrand: true,
      loading: '',
      loading2: '',
      loading3: '',
      loading4: '',
      saleSource: [],
      SaleInfosLike: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      imageUrl: '',
      imageUrl2: '',
      imageUrl3: '',
      imageUrl4: '',
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {},
      url: {
        add: '/sale/cxmSaleCarInfo/addCarInfo',
        edit: '/sale/cxmSaleCarInfo/editCarInfo',
        imgAction: 'cxm/cxmCommonBusiness/uploadPlainText',
        getStoreId: '/sale/cxmSaleStoreInfo/queryStoreMap',
        getStorekeeperId: '/sale/cxmSaleStaffInfo/queryStaffMap',
        delete: '/sale/cxmSaleCarInfo/delete',
        brandList: '/sale/cxmSaleBaseInfo/queryByTypes',
        enterpriseList: '/sale/cxmSaleRelatedEnterprise/queryEnterpriseListByTypes',
        loadImg: 'cxm/cxmCommonBusiness/downloadPlainText'
      },
      showDing: false,
      showEnterpriseUscc: false,
      headers: '',
      picData: {},
      storeName: [],
      storeId: [],
      selectItem: [1, 2, 3, 4, 5],
      keyWordsList: [],
      consultationType: [
        {
          key: 1,
          value: '政策文件类'
        }, {
          key: 2,
          value: '申请流程类'
        }, {
          key: 3,
          value: '需求咨询类'
        }, {
          key: 4,
          value: '建议意见类'
        }, {
          key: 5,
          value: '投诉举报类'
        }
      ],
      handlingStatus: [
        {
          key: 1,
          value: '待处理'
        }, {
          key: 2,
          value: '已处理'
        }
      ],
      storekeeperName: [],
      storekeeperId: [],
      checkboxgroupvalue: [],
      checkboxgroupvalue2: [],
      brandList: [],
      brandListAll: [],
      colorList: [],
      carModel: [],
      carModelAll: [],
      inColorList: [],
      supplierList: {},
      manufacturerList: {},
      shouxuList: [],
      zhuangbeiList: [],
      appearanceImg: '',
      qrCodeImg: '',
      nameplateImg: '',
      certificateImg: '',
      backup: {}
    }
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN)
    this.headers = { 'X-Access-Token': token, 'Content-Type': 'application/x-www-form-urlencoded' }

  },
  computed: {
    importImgAction: function() {
      return `${process.env.VUE_APP_BASE_API}${this.url.imgAction}`
    }
  },
  methods: {
    ...mapGetters(['nickname', 'avatar', 'userInfo']),
    showModal() {
      this.modalShow = true
    },
    show(record) {
      this.record = record
      this.visible = true
    },
    hideModal() {
      this.modalShow = false
    },

    add(record) {
      console.log(record)
      this.edit(record)
    },
    edit(record, type) {
      this.type = type
      this.record = record

      this.form.resetFields()
      this.visible = true
      let httpurl = '/cxm/knowledgeBase/queryById' + '?id=' + record.id
      getAction(httpurl, {})
        .then((res) => {
          if (res.success) {
            this.$emit('ok')
            this.model = res.result
            // console.log(this.model)
            // console.log(this.model.fileId)
            this.visible = true
            if (this.model.fileId) {
              // this.fileList = [{

              // uid: '-1',
              // name: '',
              // status: 'done',
              // url: `${process.env.VUE_APP_BASE_API}${this.url.loadImg}?id=${this.model.fileId}`
              // }]
              // console.log(this.fileList)
              // console.log(this.model)

              this.fileList.push({
                // uid: this.model[i].fileId,
                uid: this.model.fileId,
                name: this.model.fileName,//文件名
                // name: this.model.fileId,
                status: 'done'
              })

            }

            if (this.model.type) {
              this.backup.type = this.model.type
              this.model.type = Number(this.model.type)
              switch (this.model.type) {
                case '0':
                  this.model.type = '政策文件类'
                  break
                case '1':
                  this.model.type = '申请流程类'
                  break
                case '2':
                  this.model.type = '需求咨询类'
                  break
                case '3':
                  this.model.type = '建议意见类'
                  break
                case '4':
                  this.model.type = '投诉举报类'
                  break
              }
            }

            this.model.keywords = this.model.keywords ? this.model.keywords.split(',') : null
            this.$nextTick(() => {

              this.form.setFieldsValue({
                type: this.model.type,
                tittle: this.model.tittle,
                url: this.model.url,
                content: this.model.content,
                keywords: this.model.keywords
              })

            })
          } else {
            this.$message.warning(res.message)
          }
        })

      getAction('/cxm/knowledgeBase/getKeyWords', {})
        .then((res) => {
          // console.log(res)
          if (res.success) {
            // console.log(res)
            this.keyWordsList = res.result
            // console.log( this.keyWordsList)
          }

        })
    },

    downloadFile() {
      console.log(this.record.fileId)
      if (this.record.fileId !== '' || this.record.fileId !== null) {
        window.location.href = 'http://192.168.77.231:9088/cxmsystem/cxm/knowledgeBase/public/read?id=' + this.record.fileId
      } else if (this.record.fileId == '' || this.record.fileId == null) {
        this.$message.warning('暂无文件')
      }
      // getAction('cxm/knowledgeBase/public/read?id=' + this.record.fileId)
      //   .then((res) => {
      //     console.log(res)
      //     if (res.success) {
      //       console.log(res)
      //
      //       this.$message.success(res.message)
      //     } else {
      //       this.$message.warning(res.message)
      //     }
      //   })
    },

    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeUpload(file) {
      this.fileList = [...this.fileList, file]
      console.log(this.fileList)
      this.upload(file)
      return false
    },

    upload(file) {
      console.log(file)
      let fileList = this.fileList

      // 1. Limit the number of uploaded files
      //    Only to show two recent uploaded files, and old ones will be replaced by the new
      if (fileList.length > 1) {
        fileList = fileList.slice(-1)
        this.$message.warning('仅允许上传单份文件，已覆盖原文件')
      }

      // 2. read from response and show file link
      fileList = fileList.map(file => {
        if (file.response) {
          // Component will show file.url as link
          file.url = file.response.url
        }
        return file
      })

      this.fileList = fileList
      console.log(this.fileList)
      this.file = file
      console.log(this.file)

    },

    close() {
      this.$emit('close')
      this.imageUrl = null
      this.imageUrl1 = null
      this.imageUrl2 = null
      this.imageUrl3 = null
      this.imageUrl4 = null
      this.appearanceImg = null
      this.qrCodeImg = null
      this.nameplateImg = null
      this.certificateImg = null
      this.visible = false
      this.fileList = []
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {

        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'post'
          }
          //
          // this.model.keywords = this.model.keywords ? this.model.keywords.join(',') : null
          // let formData = Object.assign(this.model, values)
          let formData = new FormData()

          // 赋值与判空
          if (values.content) {
            formData.append('content', values.content)
          }
          if (this.record.id) {
            formData.append('id', this.record.id)
          }
          // if (values.fileId) {
          //   formData.append('fileId', values.fileId)
          // }
          if (values.tittle) {
            formData.append('tittle', values.tittle)
            //后端字段为tittle不是title
          }
          if (values.url) {
            formData.append('url', values.url)
          }
          if (values.type) {
            if (typeof (values.type) == 'string') {
              values.type = this.backup.type
            } else {
              formData.append('type', values.type)
            }
          }
          if (values.keywords) {
            formData.append('keywords', values.keywords)
          }
          // if (this.fileList !== []) {
          //   if (this.fileList[0].size) {
          //     formData.append('file', this.fileList[0])
          //   }
          // }
          if (this.fileList !== []) {
            formData.append('file', this.fileList[0])
          }

          //时间格式化
          /* formData.orderDate = formData.orderDate ? formData.orderDate.format('YYYY-MM-DD HH:mm:ss') : null */

          httpAction('/cxm/knowledgeBase/edit', formData, method)
            .then((res) => {
              if (res.success) {
                console.log(res)
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              this.noChooseBrand = true
              that.$parent.$parent.loadData()
              that.close()
            })
        } else {
          this.$message.warning('请上传文件')
        }
      })
    },
    handleCancel() {
      this.close()
      this.fileList = []
    },
    onChange(checkedValues) {
      console.log('checked = ', checkedValues)
      console.log('value = ', this.value)
    },
    onChange2(checkedValues) {
      console.log('checked = ', checkedValues)
      console.log('value = ', this.value)
    }
  }
}
</script>

<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.ant-upload-select-picture-card img {
  width: 128px;
  height: 128px;
}

.BottomButtons {
  text-align: center;
  margin-top: 70px;
}

.titleText {
  margin: 0 0 15px 5%;
}
</style>